import socket
import selectors
from selectors import SelectorKey
from typing import List, Tuple

selector = selectors.DefaultSelector()

# 创建一个TCP服务器套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#  将SO_REUSEADDR 设置为1，表示重复使用此端口，避免出现address already In use错误。
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 将套接字的地址设置为127.0.0.1:8000
address = ("127.0.0.1", 8000)
server_socket.bind(address)
# 开启监听传入的连接
server_socket.listen()

selector.register(server_socket, selectors.EVENT_READ)
while True:
    # 创建一个将在1秒后超时的选择器
    events: List[Tuple[SelectorKey, int]] = selector.select(timeout=1)

    if len(events) == 0:
        print("没有事件")
    for event, _ in events:
        # 获取事件的套接字，该套接字存储在fileobj字段中
        event_socket = event.fileobj
        if event_socket == server_socket:
            # 等待连接
            connection, client_address = server_socket.accept()
            # 将客户端套接字标记为非阻塞
            connection.setblocking(False)
            print(f"从{client_address}获取一个连接")
            # 注册与选择器连接的客户端
            selector.register(connection, selectors.EVENT_READ)
        else:
            # 如果事件套接字不是服务器套接字，则从客户端接收数据，并将其回显
            data = event_socket.recv(1024)
            print(f"获取数据{data}")
            event_socket.send(data)
